package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sun.misc.Request;

import java.util.List;

@Service
public class DubboCartServiceImpl implements DubboCartService{

    @Autowired
    private CartMapper cartMapper;


    @Override
    public List<Cart> findCartList(long userId) {

        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return cartMapper.selectList(queryWrapper);
    }

    /**
     * 需求: 实现数量的更新操作
     * sql: update tb_cart set num = #{num},updated=#{updated}
     *      where user_id = #{userId} and item_id=#{itemId}
     * @param cart
     */
    @Override
    @Transactional
    public void updateCartNum(Cart cart) {//itemId/userId/num
        Cart tempCart = new Cart();
        tempCart.setNum(cart.getNum());
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("item_id", cart.getItemId());
        updateWrapper.eq("user_id", cart.getUserId());
        cartMapper.update(tempCart,updateWrapper);
    }

    //如果用户重复加购,则只做数量的修改
    //根据userId和itemId 判断数据是否有值
    @Override
    @Transactional
    public void saveCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("item_id", cart.getItemId());
        Cart cartDB = cartMapper.selectOne(queryWrapper);
        if(cartDB == null){ //表示数据库中没有记录,直接入库
            cartMapper.insert(cart);
        }else{  //数据库中有记录 只改数量
            int num = cart.getNum() + cartDB.getNum();
            //1.手写sql 2.简洁封装
            Cart cartTemp = new Cart();
            cartTemp.setId(cartDB.getId()).setNum(num);
            cartMapper.updateById(cartTemp);
        }
    }

    @Override
    public void deleteCarts(Cart cart) {

        cartMapper.delete(new QueryWrapper<>(cart));
    }
}
